#!/usr/bin/env ruby

require 'ldap'
require 'ldap/control'
require 'customer'

class Auth

  def initialize(ldap_server, customer_dn)
    @ldap_server = ldap_server
    @customer_dn = customer_dn
  end

  def get_customer(username, password)
    customer = nil
    ldap = LDAP::Conn.new(@ldap_server)    
    login_dn = sprintf(@customer_dn, username)
    begin
      ldap.bind(login_dn, password) { |session| 
        ldap.search2(login_dn, 
          LDAP::LDAP_SCOPE_SUBTREE, '(objectclass=*)', ['credit']) { |entry|
          credit = entry['credit'][0].to_i
          customer = Customer.new(username, credit)
        }
      }
    rescue
      puts "invalid login"
    end
    customer
  end
end